package code.excel.jxl;

import java.io.File;
import java.io.IOException;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
* <p></p>
*
* @version 1.0
* @author:huangwf
* @date:2017/8/17 15:32
* @history
*/

public class ExcelHandleJxlExample {


/**
* <p>读取Excel</p>
*
* @author:huangwf
* @date:2017/8/17 15:37
* @version 1.0
* @history
*/
public static void ReadExcelJxl(String filePath, String fileName) throws IOException, BiffException {

File xlsFile = new File(filePath + fileName);
// 获得工作簿对象
Workbook workbook = Workbook.getWorkbook(xlsFile);
// 获得所有工作表
Sheet[] sheets = workbook.getSheets();
// 遍历工作表
if (sheets != null) {
for (Sheet sheet : sheets) {
// 获得行数
int rows = sheet.getRows();
// 获得列数
int cols = sheet.getColumns();
// 读取数据
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
System.out.printf("%10s", sheet.getCell(col, row)
.getContents());
}
System.out.println();
}
}
}
workbook.close();
}

/**
* <p>写入Excel</p>
*
* @author:huangwf
* @date:2017/8/17 15:37
* @version 1.0
* @history
*/
public static void wirteExcelJxl(String filePath, String fileName) throws IOException {

File excelFile = new File(filePath + fileName);

if (excelFile.exists()) {
excelFile.createNewFile();
}
// 创建一个工作簿
WritableWorkbook workbook = Workbook.createWorkbook(excelFile);
// 创建一个工作表
WritableSheet sheet = workbook.createSheet("jxl", 0);//sheet名称及列
try {
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
// 向工作表中添加数据
sheet.addCell(new Label(col, row, "data" + row + col));
}
}
workbook.write();
workbook.close();
} catch (WriteException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

try {
String path = "excel/out/excel/";
String name = "jxl.xls";
wirteExcelJxl(path, name);
ReadExcelJxl(path, name);
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
}
}
